<template>
  <div class="address">
    <van-nav-bar
      :title="aid ? '编辑地址' : '新增地址'"
      left-text="返回"
      @click-left="back"
      left-arrow
    />
    <van-address-edit
      :area-list="areaList"
      show-postal
      :show-delete="!!aid"
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      :address-info="defaultAddress"
      @save="save"
      @delete="deleteAddress"
    />
  </div>
</template>

<script>
import areaList from "../assets/js/area.js";
import "../assets/less/address.less";
export default {
  name: "Address",
  data() {
    return {
      areaList,
      aid: "",
      defaultAddress: {},
    };
  },

  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.aid = vm.$route.params.aid;
      if (vm.aid) {
        vm.getAddressByAid();
      }
    });
  },

  methods: {
    back() {
      this.$router.back();
    },

    save(v) {
      if (this.aid) {
        this.editAddress(v);
      } else {
        this.addAddress(v);
      }
    },

    // 新增地址
    addAddress(v) {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      let data = {
        ...v,
        appkey: this.appkey,
        tokenString,
      };

      data.isDefault = Number(data.isDefault);
      delete data.country;
      console.log(data);

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "POST",
        url: this.baseURL + "/addAddress",
        data,
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 9000) {
            this.$router.push({ name: "AddressList" });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 编辑地址
    editAddress(v) {
      let isEdit = false;

      for (let key in this.defaultAddress) {
        if (this.defaultAddress[key] !== v[key]) {
          isEdit = true;
          break;
        }
      }

      if (isEdit) {
        let tokenString = this.$cookies.get("tokenString");

        if (!tokenString) {
          console.log("浏览器token不存在");
          return this.$router.push({ name: "Login" });
        }

        let address = {};
        address.aid = this.aid;
        address.name = v.name;
        address.tel = v.tel;
        address.province = v.province;
        address.city = v.city;
        address.county = v.county;
        address.addressDetail = v.addressDetail;
        address.areaCode = v.areaCode;
        address.postalCode = v.postalCode;
        address.isDefault = Number(v.isDefault);

        this.$toast.loading({
          message: "加载中...",
          forbidClick: true,
          duration: 0,
        });

        this.axios({
          method: "POST",
          url: this.baseURL + "/editAddress",
          data: {
            appkey: this.appkey,
            tokenString,
            ...address,
          },
        })
          .then((response) => {
            this.$toast.clear();
            // console.log(response);

            if (response.data.code === 700) {
              this.$toast({
                message: response.date.msg,
                forbidClick: true,
                duration: 1000,
              });
              this.$router.push({ name: "Login" });
            }

            if (response.data.code === 30000) {
              this.$router.push({ name: "AddressList" });
            }
          })
          .catch((err) => {
            this.$toast.clear();
            console.error(err);
          });
      } else {
        console.log("未编辑");
        this.$router.push({ name: "AddressList" });
      }
    },

    // 删除地址
    deleteAddress(v) {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "POST",
        url: this.baseURL + "/deleteAddress",
        data: {
          appkey: this.appkey,
          tokenString,
          aid: v.aid,
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.data.msg,
              forbidClick: true,
              duration: 2000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 10000) {
            this.$router.push({ name: "AddressList" });
            this.$toast({
              message: response.data.msg,
              forbidClick: true,
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 根据aid获取地址
    getAddressByAid() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "GET",
        url: this.baseURL + "/findAddressByAid",
        params: {
          appkey: this.appkey,
          tokenString,
          aid: this.aid,
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 40000) {
            if (response.data.result[0].isDefault) {
              response.data.result[0].isDefault = !!response.data.result[0].isDefault;
            }
            this.defaultAddress = response.data.result[0];
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },
  },
};
</script>
